package com.msb.dongbao.portal.web.controller.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.msb.dongbao.portal.web.controller.posttest.SignDTO;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api-safe")
public class ApiSafeController {

    @GetMapping("/hello")
    public  String hello(){
        return "hello api";
    }

    /***
     * 测试 参数防篡改
     * 用户参数，用户的签名。
     * sign1=Md5/sha256(age=10name=张三appSecret=xxx)
     * 传给后端：name=李四&age=10&sign=xxxxxxx，
     * sign2=Md5/sha256(age=10name=李四appSecret=xxx)
     * @return
     */
    @RequestMapping("/get-test")
    public String getTest(String appId, String name, String sign, HttpServletRequest  request){
        Map<String ,String> map =  new HashMap<>();
//        map.put("appid",appId);
//        map.put("name",name);

        Enumeration<String> parameterNames = request.getParameterNames();
        while(parameterNames.hasMoreElements()){
            //获取name
            String parametername = parameterNames.nextElement();
            //获取值
            String parameterValue = request.getParameter(parametername);
            System.out.println("key="+parametername + "  value="+parameterValue);
            map.put(parametername,parameterValue);
        }

//        long time = System.currentTimeMillis() - timeStamp;
//        if(time>1000*10){
//            return "接口过期了";
//        }
        String s = CheckUtils.generatorSign(map);
        System.out.println(s);
        if(s.equals(sign)){
            return "校验通过";
        }else{
            return "校验不通过";
        }
    }

    @PostMapping("/post-test")
    public  String postTest(@RequestBody SignDTO signDTO){
        JSONObject obj = JSONUtil.parseObj(signDTO);
        System.out.println("controller参数："+ obj);
//        //参数转map
////        Map<String, String> stringObjectMap = Convert.toMap(String.class, String.class,obj);
////        //排序
////        Map<String, String> stringStringMap = CheckUtils.sortMapByKey(stringObjectMap);
////        System.out.println(stringStringMap);
////        //map生成签名
////        //客户端传过来的
////        String signClient = stringStringMap.get("sign");
////        String signSever = CheckUtils.generatorSign(stringStringMap);
////        if(signClient.equals(signSever)){
////            return "校验通过";
////        }else{
////            return "校验不通过";
////        }
        return "controller";
    }
}
